package bit.springtransdemo.controller;

import bit.springtransdemo.service.LogService;
import bit.springtransdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RequestMapping("/user")
@RestController
//@Transactional//作用域是public,基于AOP实现
//@Transactional(rollbackFor = Exception.class)
//@Transactional
@Transactional(isolation=Isolation.DEFAULT)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;


//    @Autowired
//    private DataSourceTransactionManager transactionManager;
//
//    @Autowired
//    private TransactionDefinition transactionDefinition;
//
//    @RequestMapping("/registry")
//    public String registry( String userName, String password){
//        TransactionStatus transactionStatus=transactionManager.getTransaction(transactionDefinition);
//        userService.registryUser(userName,password);
////        transactionManager.commit(transactionStatus);
//        transactionManager.rollback(transactionStatus);
//        return "注册成功";
//    }

//    @RequestMapping("/registry")
//    String registry2( String userName, String password){
//        userService.registryUser(userName,password);
//        try{
//            int a=10/0;
//        }catch(Exception e){
//            log.info("算数异常");
////            throw e;//回滚了,去掉就不会回滚
//        //手动回滚事务
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
//
//
//        return "注册成功";
//    }

    @RequestMapping("/registry")
    String registry3( String userName, String password) throws Exception {
        userService.registryUser(userName,password);
        logService.insertLog(userName,"用户注册");
//            if(1==1){
//                throw new IOException();
//            }


        return "注册成功";
    }
}
